/* Octopus PDF - A simple document viewer for Android.
   Copyright (C) 2013  Gerald Thaler

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */
package de.geraldthaler.octopuspdf.view;


/**
 * @author Gerald Thaler
 */
public final class FpsMeter {
    private int count;
    private float frameDuration = 0.01f;
    private boolean running = false;
    private long startTime;

    public void frame() {
        final long now = System.nanoTime();
        if (!running) {
            start(now);
            return;
        }
        if (++count == 5) {
            stop(now);
            start(now);
        }
    }

    public float getFrameDuration() {
        return frameDuration;
    }
    
    public void stop() {
        if (!running)
            return;
        stop(System.nanoTime());
        running = false;
    }

    private void start(final long now) {
        count = 0;
        running = true;
        startTime = now;
    }

    private void stop(final long now) {
        if (count > 4)
            frameDuration = (frameDuration * 16f + (now - startTime) * 1e-9f) / (16f + count);
    }
}
